#include <func.h>

#define MAXPATH 1024

void dfs_print(const char* path, int width);	/* width: 缩进的空格数目 */

int directories = 0, files = 0;

int main(int argc, char *argv[])
{
    // ./t_tree dir
    if (argc != 2) {
        fprintf(stderr, "Usage: %s dir\n", argv[0]);
        exit(1);
    }

    puts(argv[1]);		// 打印目录的名字

    dfs_print(argv[1], 4);	// 递归打印每一个目录项

    printf("\n%d directories, %d files\n", directories, files);		// 最后打印统计信息
    return 0;
}

void dfs_print(const char* path, int width) 
{
    // 1. 打开目录流
    DIR* stream = opendir(path);
    if (!stream) {
        perror("opendir()");
        exit(1);
    }
    // 2. 递归地打印每一目录项
    errno = 0;
    struct dirent* curr;
    while ((curr = readdir(stream)) != NULL) {
        // 忽略以 . 开头的文件
        char* filename = curr->d_name;
        if (filename[0] == '.') {
            continue;
        }
        // 打印目录项
        for (int i = 0; i < width; i++) {
            putchar(' ');
        }
        puts(filename);
        if (curr->d_type == DT_REG) {
            // 普通文件
            files++;
        } else if (curr->d_type == DT_DIR) {
            // 目录
            directories++;
            // 递归处理子目录
            char subpath[MAXPATH];
            sprintf(subpath, "%s/%s", path, filename); /* 拼接路径 */
            dfs_print(subpath, width + 4);
        }
    }
    if (errno) {
        perror("readdir()");
        exit(1);
    }
    // 3. 关闭目录流
    closedir(stream);
}
